package com.dayaokeji.rhythmschoolstudent.service;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Build;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import android.text.TextUtils;
import android.util.Log;

import com.dayaokeji.rhythmschoolstudent.BuildConfig;
import com.dayaokeji.rhythmschoolstudent.R;
import com.dayaokeji.rhythmschoolstudent.client.common.base.App;
import com.dayaokeji.rhythmschoolstudent.client.common.base.Constant;
import com.dayaokeji.rhythmschoolstudent.client.main.MainActivity;
import com.dayaokeji.rhythmschoolstudent.client.mine.account.bean.RemoteHostPicker;
import com.dayaokeji.rhythmschoolstudent.event.AppStateEvent;
import com.dayaokeji.rhythmschoolstudent.utils.AndroidUtils;
import com.dayaokeji.rhythmschoolstudent.utils.RemoteHostUtil;
import com.dayaokeji.rhythmschoolstudent.utils.ServerCallback;
import com.dayaokeji.rhythmschoolstudent.utils.UserUtils;
import com.dayaokeji.server_api.ApiUtils;
import com.dayaokeji.server_api.ServerResponse;
import com.dayaokeji.server_api.api.SystemApi;
import com.dayaokeji.server_api.domain.AppState;
import com.dayaokeji.server_api.domain.UserInfo;
import com.orhanobut.logger.Logger;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import me.jessyan.retrofiturlmanager.RetrofitUrlManager;
import retrofit2.Call;

/**
 * Created by Gorden on 2018/3/24.
 * App状态服务
 */

public class AppStateService extends Service {

    public static final String TAG = AppStateService.class.getSimpleName();

    public static final Integer SLEEP = 25;

    private static final String NOTIFICATION_CHANNEL = "在线状态";

    private final SystemApi systemApi = ApiUtils.getApi(SystemApi.class);
    private static Call<ServerResponse<Void>> appStateCall;
    private static boolean isReq = true;
    private static int state = 1;
    private NotificationManager mNotificationManager;
    private static final CompositeDisposable compositeDisposable = new CompositeDisposable();

    @Override
    public void onCreate() {
        super.onCreate();
        EventBus.getDefault().register(this);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        uploadAppState();
        buildNotification();
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        isReq = false;
        if (appStateCall != null) {
            appStateCall.cancel();
        }
        stopForeground(true);
        EventBus.getDefault().unregister(this);
        compositeDisposable.clear();
        super.onDestroy();
    }


    private void buildNotification() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            @SuppressLint("WrongConstant")
            NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL,"律动校园", NotificationManager.IMPORTANCE_DEFAULT);
            notificationChannel.setLightColor(Color.GREEN);
            getNotificationManager().createNotificationChannel(notificationChannel);
        }
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this.getApplicationContext(), NOTIFICATION_CHANNEL);
        builder.setLargeIcon(BitmapFactory.decodeResource(this.getResources(),R.mipmap.ic_launcher))
                .setContentTitle("律动校园")
                .setSmallIcon(R.mipmap.ic_launcher)
                .setWhen(System.currentTimeMillis()); // 设置该通知发生的时间
        builder.setSmallIcon(R.mipmap.ic_launcher);
        builder.setBadgeIconType(Notification.BADGE_ICON_SMALL);
        builder.setContentIntent(getPendingIntent());
        Notification notification = builder.build();
        notification.flags = Notification.FLAG_SHOW_LIGHTS;
        startForeground(1,notification);
    }

    private NotificationManager getNotificationManager() {
        if (mNotificationManager == null) {
            mNotificationManager =
                    (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        }
        return mNotificationManager;
    }

    private PendingIntent getPendingIntent() {
        Intent openMainIntent = new Intent(this, MainActivity.class);
        TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
        stackBuilder.addParentStack(MainActivity.class);
        stackBuilder.addNextIntent(openMainIntent);
        return stackBuilder.getPendingIntent(0, PendingIntent.FLAG_ONE_SHOT);
    }

    private void uploadAppState() {
        appStateReq();
        compositeDisposable.add(Observable.interval(SLEEP, TimeUnit.SECONDS).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<Long>() {
            @Override
            public void accept(Long aLong) throws Exception {
                if (BuildConfig.DEBUG) {
                    Log.d(TAG,"keep live is req = "+isReq);
                }
                if (isReq) {
                    if (AndroidUtils.isProessRunning(AppStateService.this.getApplicationContext(), App.getInstance().getPackageName())) {
                        appStateReq();
                    }else{
                        state = Constant.APP_STATE_EXIT_CODE;
                        appStateReq();
                    }
                }
            }
        }));

    }

    private void setBaseUrl() {
        RemoteHostPicker currentRemoteHost = RemoteHostUtil.getCurrentRemoteHost();
        if (currentRemoteHost != null) {
            String host = currentRemoteHost.getHost();
            if (!TextUtils.isEmpty(host)) {
                RetrofitUrlManager.getInstance().setGlobalDomain(host);
            }
        }
    }

    private void appStateReq() {
        try{
            setBaseUrl();
            final UserInfo userInfo = UserUtils.getUserInfo();
            if ( userInfo != null) {
                if (!TextUtils.isEmpty(userInfo.getId()) && !TextUtils.isEmpty(UserUtils.getAccessToken())) {
                    final AppState appState = new AppState();
                    appState.setId(userInfo.getId());
                    appState.setAppState(state);
                    Logger.d(appState.toString());
                    appStateCall = systemApi.appSate(appState);
                    callback.setShowNetworkError(false);
                    appStateCall.enqueue(callback);
                }
            }
        }catch (Exception e) {
            e.printStackTrace();
        }

    }

    private ServerCallback<Void> callback = new ServerCallback<Void>() {
        @Override
        public void onResponse(boolean success, ServerResponse<Void> response) {
            if (success) {
                if (BuildConfig.DEBUG) {
                    Log.d(TAG,"上传AppState成功");
                }
            }
        }
    };

    @Subscribe
    public void updateAppState(AppStateEvent appStateEvent) {
        Logger.d("app state evet === "+appStateEvent.toString());
        if (appStateEvent.getCode() != state && appStateEvent.isReq()) {
            state = appStateEvent.getCode();
            if (BuildConfig.DEBUG) {
                Log.d(TAG,"switch = "+state);
            }
            appStateReq();
        }
        isReq = appStateEvent.isReq();
        state = appStateEvent.getCode();
        if (!isReq && state == Constant.APP_STATE_EXIT_CODE) {
            appStateReq();
        }
    }
}
